package com.example.demo.thread.juc;

import java.util.concurrent.CountDownLatch;

/**
 * Description: <br/>
 *
 * @author liulonglong
 * @taskId <br/>
 * @Date 2019/11/20 16:48
 * @Version 1.0
 */
public class Driver2 {
    private static final int N = 10;

    public static void main(String args[]) throws InterruptedException {
        CountDownLatch compsignal = new CountDownLatch(N);

        for (int i = 0; i < N; ++i) {
            new Thread(new Worker1(compsignal)).start();
        }

        compsignal.await();       // 主线程等待其它N个线程完成
        doSomething();
    }

    public static void doSomething() {
        System.out.println("main thread -- doSomething()");
    }
}

class Worker1 implements Runnable {
    private final CountDownLatch compSignal;

    Worker1(CountDownLatch compSignal) {
        this.compSignal = compSignal;
    }

    public void run() {
        doWork();
        compSignal.countDown(); //每个线程做完自己的事情后，就将计数器减去1
    }

    void doWork() {
        System.out.println("doWork() executed...");
    }
}